package cz.mff.curreco.services;

import java.io.File;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import cz.mff.curreco.model.MoneyItem;
import cz.mff.curreco.model.SessionObject;
import cz.mff.curreco.utils.MyDomTransformer;
import cz.mff.curreco.utils.MySaxHandler;

public class DataService implements IDataService {

	/** 
	 * @see {@link IDataService#testMethod()} 
	 */
	public String testMethod() {
		return "data z metody testMethod()";
	}

	@Override
	public void parseXML(SessionObject so) {
		String path = "data.xml";
		try {
			XMLReader parser = XMLReaderFactory.createXMLReader();
			InputSource source = new InputSource(path);
			parser.setContentHandler(new MySaxHandler(so));			
			
			parser.parse(source);
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void addItemToXML(MoneyItem newItem) {
		try {

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			dbf.setValidating(false);
			DocumentBuilder builder = dbf.newDocumentBuilder();
			Document doc = builder.parse("data.xml");
			MyDomTransformer my = new MyDomTransformer();
			my.transform(doc, newItem);

			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer writer = tf.newTransformer();
			writer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
			writer.transform(new DOMSource(doc), new StreamResult(new File(
					"data.xml")));

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public ArrayList<MoneyItem> getCoinsFromSameCountry(MoneyItem inputItem, SessionObject so) {
		String countryCode = inputItem.getCountryCode();
		ArrayList<MoneyItem> descriptors = so.getDescriptors();
		ArrayList<MoneyItem> result = new ArrayList<MoneyItem>();
		
		for (MoneyItem moneyItem : descriptors) 
		{
			if(moneyItem.getCountryCode().equals(countryCode))
			{				
				result.add(moneyItem);			
			}			
		}
		
		return result;
	}
}
